package com.ada.zip;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.EncryptionMethod;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class QRCodeGenerator {

    public static void main(String[] args) throws ZipException {

        Long time=System.currentTimeMillis();
        List<File> files=new ArrayList<>();
        for (int i = 0; i < 200; i++) {
            String data = "https://www.example.com/"+ UUID.randomUUID().toString(); // 二维码包含的数据
            String filePath = "E:\\datas\\qr\\%s.png"; // 保存的文件路径

            try {
                generateQRCodeImage(data, String.format(filePath,""+i),300);
                files.add(new File(String.format(filePath,""+i)));
            } catch (WriterException | IOException e) {
                e.printStackTrace();
            }
        }
        ZipParameters zipParameters = new ZipParameters();
        //zipParameters.setEncryptFiles(true);
        //zipParameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);

        File file=new File("E:\\datas\\filename3.zip");
        if (file.exists()){
            file.delete();
        }

        ZipFile zipFile = new ZipFile(file);
        zipFile.createSplitZipFile(files, zipParameters, true, 10485760); // u

        time=System.currentTimeMillis()-time;
        System.out.println(time/1000.0);
    }

    private static void generateQRCodeImage(String data, String filePath,int width) throws WriterException, IOException {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.MARGIN, 1);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, width, hints);

        BufferedImage bufferedImage = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < bitMatrix.getWidth(); x++) {
            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        File qrCodeFile = new File(filePath);
        ImageIO.write(bufferedImage, "png", qrCodeFile);
    }
}
